#include "bsp_inc.h"

typedef struct UartDemo_TUnionTag UartDemo_TUnion;
struct UartDemo_TUnionTag
{
    Int8 tx_buf[256];
    Int8 rx_buf[256];
    Bsp_THandle handle;
};

UartDemo_TUnion g_uart_demo_union;

extern void Delay(UInt32 ms);

char g_uart_demo_data[] = "Hello World\r\n";
char g_uart_demo_buf[256];
UInt32 g_tx_count;
UInt32 g_rx_count;

UInt32 g_test_count;
static void UartDemo_OnRecv(Bsp_THandle handle)
{
//    UInt32* test = (UInt32*)Bsp_UartGetUserData(handle);
//    *test += 1;

//    Int32 count = Bsp_UartRead(handle, g_uart_demo_buf, sizeof(g_uart_demo_buf));
//    if (count > 0)
//    {
//        g_rx_count += count;
//        count = Bsp_UartWrite(handle, g_uart_demo_buf, count);
//        if (count > 0)
//            g_tx_count += count;
//    }
}

void UartDemo_Init(void)
{
    UartDemo_TUnion* self = &g_uart_demo_union;
    Int32 count;

    self->handle = Bsp_UartCreate(1, self->tx_buf, sizeof(self->tx_buf), self->rx_buf, sizeof(self->rx_buf));
    Bsp_UartSetUserData(self->handle, &g_test_count);
    Bsp_UartSetEvent(self->handle, Bsp_kUartEventOnRecv, UartDemo_OnRecv);

    Bsp_UartOpen(self->handle, 115200, 0);

//    while (g_tx_count < 100000)
//    {
//        count = Bsp_UartWrite(self->handle, g_uart_demo_data, sizeof(g_uart_demo_data));
//        if (count == 0)
//            g_tx_count += count;
//        else if (count > 0)
//            g_tx_count += count;
//        
//        Delay(1);
//    }
//    Delay(1000);
//    
//    while (g_rx_count < 100000)
//    {
//        count = Bsp_UartRead(self->handle, g_uart_demo_buf, sizeof(g_uart_demo_buf));
//        if (count > 0)
//            g_rx_count += count;
//    }
//    Delay(1000);

    while (g_rx_count < 100000)
    {
        count = Bsp_UartRead(self->handle, g_uart_demo_buf, sizeof(g_uart_demo_buf));
        if (count > 0)
        {
            g_rx_count += count;
        //     count = Bsp_UartWrite(self->handle, g_uart_demo_buf, count);
        //     if (count > 0)
        //         g_tx_count += count;
        }
        // Delay(1);
    }
}
